package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    public static ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal();

    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();
        System.out.println("主线程id：" + Thread.currentThread().getId());

        //获得主线程（老请求）上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("异步线程1id：" + Thread.currentThread().getId());
            //将该线程上下文设置为主线程（老请求）上下文数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.查询收获地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);


        CompletableFuture<Void> getCartItemsFuture = CompletableFuture.runAsync(() -> {
            System.out.println("异步线程2id：" + Thread.currentThread().getId());
            //将该线程上下文设置为主线程（老请求）上下文数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.查询购物车数据
            List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
            orderConfirmVo.setItems(userCartItems);
        }).thenRun(() -> {
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStock(skuIds);
            List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        });


        CompletableFuture.allOf(getAddressFuture, getCartItemsFuture).get();
        //3.设置积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4.其他数据自动计算

        //5.TODO 防重令牌
        String orderToken = UUID.randomUUID().toString();
        //为redis存入orderToken
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), orderToken, 30, TimeUnit.MINUTES);
        //为返回给前端页面vo存入orderToken，用以比对，接口幂等性
        orderConfirmVo.setOrderToken(orderToken);
        return orderConfirmVo;
    }

    //@GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);
        MemberRespVo loginUser = LoginInterceptor.loginUser.get();
        confirmVoThreadLocal.set(vo);
        //比对令牌,lua脚本确定原子性
        String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId()), vo.getOrderToken());

        if (result == 0L) {
            // 失败
            responseVo.setCode(1);
        } else {
            //1.创建订单
            OrderCreateTo order = createOrder();
            //2.验价
            BigDecimal payPrice = order.getOrder().getPayAmount();
            BigDecimal payPrice1 = vo.getPayPrice();
            if (Math.abs(payPrice1.subtract(payPrice).doubleValue()) < 0.01) {
                //TODO 3.保存订单到数据库
                saveOrder(order);
                //4.锁库存
                WareSkuLockVo skuLockVo = new WareSkuLockVo();
                List<OrderItemEntity> orderItems = order.getOrderItems();
                List<OrderItemVo> lock = orderItems.stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                skuLockVo.setLocks(lock);
                skuLockVo.setOrderSn(order.getOrder().getOrderSn());
                //远程调用锁库存方法
                R r = wareFeignService.orderLockStock(skuLockVo);

                if (r.getCode() == 0) {
                    //锁库存成功
                    responseVo.setOrder(order.getOrder());
                    //System.out.println(1/0);
                    //发送订单消息到延迟队列
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                } else {
                    responseVo.setCode(3);
                    throw new NoStockException();
                }
            } else {
                responseVo.setCode(2);
            }

        }
        return responseVo;

    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        OrderEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    @Override
    public void closeOrder(OrderEntity orderEntity) {
        OrderEntity order = this.getById(orderEntity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(order.getStatus())) {
            OrderEntity update = new OrderEntity();
            update.setId(order.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            //更新状态为已取消
            this.updateById(update);

            //属性对拷
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(order,orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    /**
     * 创建秒杀单
     * @param orderTo
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {

        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //TODO 保存商品的spu信息
        //R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
        //SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        //});
        //orderItem.setSpuId(spuInfoData.getId());
        //orderItem.setSpuName(spuInfoData.getSpuName());
        //orderItem.setSpuBrand(spuInfoData.getBrandName());
        //orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }


    private void saveOrder(OrderCreateTo order) {
        //保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        orderEntity.setCreateTime(new Date());
        this.save(orderEntity);
        //保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }

    /**
     * 创建订单信息
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.生成订单号及其订单基本信息
        OrderEntity orderEntity = buildOrder();
        orderCreateTo.setOrder(orderEntity);

        //2.获取所有订单项
        List<OrderItemEntity> orderItemEntities = buildItems();
        orderCreateTo.setOrderItems(orderItemEntities);
        orderCreateTo.setOrder(orderEntity);

        //3。根据订单项目计算订单价格，积分信息
        computePrice(orderEntity, orderItemEntities);


        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            //商品价格*购买数量
            total = total.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getSkuQuantity())));

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);



    }

    List<OrderItemEntity> buildItems() {
        //下单最后一次确定价格
        List<OrderItemVo> userCartItems = cartFeignService.getUserCartItems();
        if (userCartItems.size() > 0 && userCartItems != null) {
            List<OrderItemEntity> collect = userCartItems.stream().map(item -> {
                OrderItemEntity orderItem = buildItem(item);
                return orderItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;

    }

    private OrderItemEntity buildItem(OrderItemVo item) {
        OrderItemEntity orderItem = new OrderItemEntity();
        //1.订单号
        //2.spu信息
        R spuR = productFeignService.getSpuBySkuId(item.getSkuId());
        SpuInfoVo spu = spuR.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spu.getId());
        orderItem.setSpuBrand(spu.getBrandId().toString());
        orderItem.setSpuName(spu.getSpuName());
        orderItem.setCategoryId(spu.getCatalogId());

        //3.sku信息
        orderItem.setSkuId(item.getSkuId());
        orderItem.setSkuName(item.getTitle());
        orderItem.setSkuPrice(item.getPrice());
        String attrs = String.join(";", item.getSkuAttr());
        orderItem.setSkuAttrsVals(attrs);
        orderItem.setSkuQuantity(item.getCount());
        orderItem.setSkuPic(item.getImage());
        //4.优惠信息（不做）

        //5.积分信息
        orderItem.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItem.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());

        //6.订单项的价格信息
        orderItem.setPromotionAmount(new BigDecimal(BigInteger.ZERO));
        orderItem.setCouponAmount(new BigDecimal(BigInteger.ZERO));
        orderItem.setIntegrationAmount(item.getPrice());
        orderItem.setRealAmount(item.getPrice());

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItem.getCouponAmount())
                .subtract(orderItem.getPromotionAmount())
                .subtract(orderItem.getIntegrationAmount());
        orderItem.setRealAmount(subtract);

        return orderItem;
    }

    /**
     * 生成订单号及其订单基本信息
     *
     * @return
     */
    OrderEntity buildOrder() {
        OrderEntity orderEntity = new OrderEntity();
        //1.生成订单号及其订单基本信息
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        if (r != null) {
            FareVo fareVo = r.getData(new TypeReference<FareVo>() {
            });
            orderEntity.setFreightAmount(fareVo.getFare());
            MemberAddressVo address = fareVo.getAddress();
            orderEntity.setMemberId(address.getMemberId());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverRegion(address.getRegion());
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
            orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            orderEntity.setAutoConfirmDay(7);
        }
        return orderEntity;
    }


}